import Vue from 'vue'
import VueRouter from 'vue-router'
import { Dialog } from 'vant'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path:'/login',
    name:'login',
    component: () => import('@/views/login/')
  },
  {
    path:'/',
    component: () => import('@/views/layout/'),
    children:[
      {
        path:'',//首页默认路由
        name:'home',
        component:() => import('@/views/home/')
      },
      {
        path:'/qa',//首页默认路由
        name:'qa',
        component:() => import('@/views/qa/')
      },
      {
        path:'/video',//首页默认路由
        name:'video',
        component:() => import('@/views/video/')
      },
      {
        path:'/my',//首页默认路由
        name:'my',
        component:() => import('@/views/my/')
      },
    ]
  },
  {
    path:'/search',
    name:'search',
    component: () => import('@/views/search/')
  },
  {
    path:'/article/:articleId',
    name:'article',
    component: () => import('@/views/article/'),
    props:true
  },
  {
    path:'/profile',
    name:'profile',
    component: () => import('@/views/user-profile/')
  },
  {
    path:'/user/chat',
    name:'user-chat',
    component: () => import('@/views/user-chat/'),
    meta: { requiresAuth: true }
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from ,next) =>{
  if (to.name === 'login' || !to.meta.requiresAuth) {
    return next()
  }

  if (store.state.user) {
    return next()
  }

  Dialog.confirm({
    title: '该功能需要登录，确认登录吗？'
  }).then(() => {
    next({
      name: 'login',
      query: {
        redirect: router.currentRoute.fullPath
      }
    })
  }).catch(() => {
    // on cancel
    next()
  })

})

export default router
